<template>
  <div class="container">
    <div class="search">
      <el-form :inline="true"  label-width="68px" size="small">
         <el-form-item label="商品名">
            <el-input v-model="searchData.name" placeholder="商品名"></el-input>
         </el-form-item>
      </el-form>
    </div>
    <div class="operation">
       <el-button type="primary" @click="search">搜索</el-button>
       <el-button type="primary" @click="handleAddCommodity">添加</el-button>
    </div>
    <el-table :data="listData" style="width: 100%" :height="578">
      <el-table-column prop="commodityName" :show-overflow-tooltip="true" label="商品名">
      </el-table-column>
      <el-table-column prop="status" label="状态">
        <template slot-scope="scope">
            <el-tag size="medium" :type="getStatusType(scope.row.status)">{{ getStatus(scope.row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="unit" label="单位">
      </el-table-column>
      <el-table-column prop="addTime" label="添加时间">
      </el-table-column>
      <el-table-column prop="" label="上架/下架">
       <template slot-scope="scope">
          <el-switch
            :value ="scope.row.status == 1"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="changeOnsaleStatus(scope.row)">
          </el-switch>
       </template>
      </el-table-column>
       <el-table-column prop="" label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEditCommodity(scope.row)">编辑</el-button>
          <el-button size="mini" v-if="scope.row.skuNum == 0" type="primary" @click="handleAddSku(scope.row)">添加SKU</el-button>
          <el-button size="mini" v-if="scope.row.skuNum > 0" type="info" @click="handleEditSku(scope.row)">编辑SKU</el-button>
          <el-button size="mini" type="danger" @click="handleDeleteCommodity(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="page.pageNumber"
      :page-sizes="[10,20, 50, 100, 500]"
      :page-size="page.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="page.total">
    </el-pagination>
    <el-dialog title="添加商品" width="40%" :visible="dialog == 'addCommodity'" :before-close="handleAddClose">
      <el-form :inline="false" label-position="left" :model="addData" :rules="addCommodityRules" ref="addClassification" label-width="80px" size="small" >
        <el-form-item label="商品名" prop="commodityName">
          <el-input v-model="addData.commodityName" placeholder="商品名"></el-input>
        </el-form-item>
        <el-form-item label="banner图" >
          <el-upload
              action="#" class="float-l"
              list-type="picture-card" :on-change="addBannerUrlFileChange" :file-list="addData.bannerUrl" :before-upload="beforeUploadImg"
              :auto-upload="false">
                <i slot="default" class="el-icon-plus"></i>
                <div slot="file" slot-scope="{file}">
                  <img
                    class="el-upload-list__item-thumbnail"
                    :src="file.url" alt=""
                  >
                  <span class="el-upload-list__item-actions">
                      <span class="el-upload-list__item-delete" @click="handleRemoveAddBannerUrlFile(file)">
                      <i class="el-icon-delete"></i>
                    </span>
                  </span>
                </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品主图" >
          <el-upload
              action="#" class="float-l"
              list-type="picture-card" :on-change="addMainUrlFileChange" :file-list="addData.mainUrl" :before-upload="beforeUploadImg"
              :auto-upload="false">
                <i slot="default" class="el-icon-plus"></i>
                <div slot="file" slot-scope="{file}">
                  <img
                    class="el-upload-list__item-thumbnail"
                    :src="file.url" alt=""
                  >
                  <span class="el-upload-list__item-actions">
                      <span class="el-upload-list__item-delete" @click="handleRemoveAddMainUrlFile(file)">
                      <i class="el-icon-delete"></i>
                    </span>
                  </span>
                </div>
          </el-upload>
        </el-form-item>
        <!-- <el-form-item label="状态" prop="status">
          <el-select v-model="addData.status" placeholder="请选择">
            <el-option
              v-for="item in status"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="商品分类" prop="commodityClassificationIds">
           <el-cascader
              v-model="addData.commodityClassificationIds"
              :options="classifications"
              @change="handleChangeClassification"
              :props="cascaderProps">
              </el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialog = '';clearAddCommodityData()">取 消</el-button>
        <el-button type="primary" @click="addCommodity">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="编辑商品" width="40%" :visible="dialog == 'editCommodity'" :before-close="handleEditClose">
      <el-form :inline="false" label-position="left" :model="editData" :rules="addCommodityRules" ref="addClassification" label-width="80px" size="small" >
        <el-form-item label="商品名" prop="commodityName">
          <el-input v-model="editData.commodityName" placeholder="商品名"></el-input>
        </el-form-item>
        <el-form-item label="banner图" >
          <el-upload
              action="#" class="float-l"
              list-type="picture-card" :on-change="editBannerUrlFileChange" :file-list="editData.bannerUrl" :before-upload="beforeUploadImg"
              :auto-upload="false">
                <i slot="default" class="el-icon-plus"></i>
                <div slot="file" slot-scope="{file}">
                  <img
                    class="el-upload-list__item-thumbnail"
                    :src="file.url" alt=""
                  >
                  <span class="el-upload-list__item-actions">
                      <span class="el-upload-list__item-delete" @click="handleRemoveEditbannerUrlFile(file)">
                      <i class="el-icon-delete"></i>
                    </span>
                  </span>
                </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品主图" >
          <el-upload
              action="#" class="float-l"
              list-type="picture-card" :on-change="editMainUrlFileChange" :file-list="editData.mainUrl" :before-upload="beforeUploadImg"
              :auto-upload="false">
                <i slot="default" class="el-icon-plus"></i>
                <div slot="file" slot-scope="{file}">
                  <img
                    class="el-upload-list__item-thumbnail"
                    :src="file.url" alt=""
                  >
                  <span class="el-upload-list__item-actions">
                      <span class="el-upload-list__item-delete" @click="handleRemoveEditMainUrlFile(file)">
                      <i class="el-icon-delete"></i>
                    </span>
                  </span>
                </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品分类" prop="commodityClassificationIds">
           <el-cascader
              v-model="editData.commodityClassificationIds"
              :options="classifications"
              @change="handleChangeEditClassification"
              :props="cascaderProps">
              </el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialog = '';clearEditCommodityData()">取 消</el-button>
        <el-button type="primary" @click="editCommodity">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import api from '@/config/server.js'
export default {
  data () {
    return {
      listData: [],
      searchData: {
        name: ''
      },
      page: {
        pageNumber: 1,
        pageSize: 10,
        total: 0,
        totalPage: 0
      },
      dialog: '',
      addData: {
        commodityName: '',
        status: null,
        info: '',
        sketch: '',
        commodityBrandId: null,
        commodityClassificationIds: [],
        commodityClassificationId: null,
        mainUrl: [],
        bannerUrl: []
      },
      classifications: [],
      addCommodityRules: {},
      editData: {
        id: null,
        commodityName: '',
        status: null,
        info: '',
        sketch: '',
        commodityBrandId: null,
        commodityClassificationIds: [],
        commodityClassificationId: null,
        mainUrl: []
      },
      status: [
        {
          value: '1',
          label: '正常'
        },
        {
          value: '2',
          label: '未上架'
        }
      ],
      cascaderProps: {
        value: 'id',
        label: 'label'
      }
    }
  },
  created () {
    this.search()
    this.getClassificationList()
  },
  methods: {
    getClassificationList () {
      api.commodityClassficationList().then((res) => {
        this.classifications = res.result
      })
    },
    search () {
      api.commodityList({
        page: this.page.pageNumber - 1,
        size: this.page.pageSize,
        name: this.searchData.name,
        description: this.searchData.description
      }).then((res) => {
        this.listData = res.result.content
        this.page.pageNumber = res.result.pageable.pageNumber + 1
        this.page.pageSize = res.result.pageable.pageSize
        this.page.total = res.result.totalElements
        this.page.totalPage = res.result.totalPages
      })
    },
    handleSizeChange (val) {
      this.page.pageSize = val
      this.search()
    },
    handleCurrentChange (val) {
      this.page.pageNumber = val
      this.search()
    },
    getStatus (status) {
      switch (status) {
        case 1:
          return '正常'
        case 2:
          return '已下架'
        default:
          return ''
      }
    },
    getStatusType (status) {
      switch (status) {
        case 1:
          return ''
        case 2:
          return 'danger'
        default:
          return ''
      }
    },
    handleAddCommodity () {
      this.dialog = 'addCommodity'
    },
    handleChangeClassification (val) {
      this.addData.commodityClassificationIds = val
    },
    clearAddCommodityData () {
      this.addData = {
        commodityName: '',
        status: null,
        info: '',
        sketch: '',
        commodityBrandId: null,
        commodityClassificationIds: [],
        commodityClassificationId: [],
        mainUrl: [],
        bannerUrl: []
      }
    },
    addCommodity () {
      console.log(this.addData)
      api.addCommodity({
        commodityName: this.addData.commodityName,
        status: this.addData.status,
        info: this.addData.info,
        sketch: this.addData.sketch,
        commodityBrandId: 1,
        commodityClassificationId: this.addData.commodityClassificationIds[this.addData.commodityClassificationIds.length - 1],
        mainUrl: this.addData.mainUrl.reduce((sum, item, index) => {
          if (index !== (this.addData.mainUrl.length - 1)) {
            return sum + item.url + ','
          } else {
            return sum + item.url
          }
        }, ''),
        bannerUrl: this.addData.bannerUrl.reduce((sum, item, index) => {
          if (index !== (this.addData.bannerUrl.length - 1)) {
            return sum + item.url + ','
          } else {
            return sum + item.url
          }
        }, '')
      }).then((res) => {
        if (res.ret === 1) {
          this.$message('添加成功')
          this.dialog = ''
          this.search()
          this.clearAddCommodityData()
        } else {
          this.$message(res.msg)
        }
      })
    },
    addMainUrlFileChange (file, fileList) {
      console.log(file, fileList)
      const form = new FormData()
      // 文件对象
      form.append('img', file.raw)
      api.upLoadImg(form).then((res) => {
        if (res.ret === 1) {
          let fileUrl = res.result
          file.url = fileUrl
          this.addData.mainUrl.push(file)
        }
      })
    },
    handleRemoveAddMainUrlFile (file) {
      var index = this.addData.mainUrl.indexOf(file)
      if (index > -1) {
        this.addData.mainUrl.splice(index, 1)
      }
    },
    addBannerUrlFileChange (file, fileList) {
      console.log(file.url, fileList)
      const form = new FormData()
      // 文件对象
      form.append('img', file.raw)
      api.upLoadImg(form).then((res) => {
        if (res.ret === 1) {
          let fileUrl = res.result
          file.url = fileUrl
          this.addData.bannerUrl.push(file)
        }
      })
    },
    handleRemoveAddBannerUrlFile (file) {
      var index = this.addData.bannerUrl.indexOf(file)
      if (index > -1) {
        this.addData.bannerUrl.splice(index, 1)
      }
    },
    handleAddClose () {
      this.dialog = ''
      this.clearAddCommodityData()
    },
    handleEditCommodity (row) {
      console.log(row)
      api.commodityInfo(row.id).then((res) => {
        let commodityInfo = res.result
        let path = commodityInfo.commodityClassificationDTO.path.split('-')
        let intPath = path.map(item => {
          return parseInt(item)
        })
        this.editData = {
          id: row.id,
          commodityName: commodityInfo.commodityName,
          status: commodityInfo.status,
          info: commodityInfo.info,
          sketch: commodityInfo.sketch,
          commodityBrandId: commodityInfo.brandInfo.id,
          commodityClassificationIds: intPath,
          commodityClassificationId: commodityInfo.commodityClassificationDTO.classificationId,
          mainUrl: row.mainUrl ? row.mainUrl.split(',').map(item => {
            return {
              url: item
            }
          }) : [],
          bannerUrl: row.bannerUrl ? row.bannerUrl.split(',').map(item => {
            return {
              url: item
            }
          }) : []
        }
        this.dialog = 'editCommodity'
      })
    },
    clearEditCommodityData () {
      this.editData = {
        id: null,
        commodityName: '',
        status: null,
        info: '',
        sketch: '',
        commodityBrandId: null,
        commodityClassificationIds: [],
        commodityClassificationId: null,
        mainUrl: []
      }
    },
    editCommodity () {
      console.log(this.editData)
      api.editCommodity(this.editData.id, {
        commodityName: this.editData.commodityName,
        status: this.editData.status,
        info: this.editData.info,
        sketch: this.editData.sketch,
        commodityBrandId: this.editData.commodityBrandId,
        commodityClassificationId: this.editData.commodityClassificationIds[this.editData.commodityClassificationIds.length - 1],
        mainUrl: this.editData.mainUrl.reduce((sum, item, index) => {
          if (index !== (this.editData.mainUrl.length - 1)) {
            return sum + item.url + ','
          } else {
            return sum + item.url
          }
        }, ''),
        bannerUrl: this.editData.bannerUrl.reduce((sum, item, index) => {
          if (index !== (this.editData.bannerUrl.length - 1)) {
            return sum + item.url + ','
          } else {
            return sum + item.url
          }
        }, '')
      }).then((res) => {
        if (res.ret === 1) {
          this.$message('修改成功')
          this.search()
          this.dialog = ''
          this.clearEditCommodityData()
        } else {
          this.$message(res.msg)
        }
      })
    },
    handleChangeEditClassification (val) {
      this.editData.commodityClassificationIds = val
    },
    editUpLoadFile (params) {
    },
    editMainUrlFileChange (file, fileList) {
      const form = new FormData()
      // 文件对象
      form.append('img', file.raw)
      api.upLoadImg(form).then((res) => {
        if (res.ret === 1) {
          let fileUrl = res.result
          file.url = fileUrl
          this.editData.mainUrl.push(file)
        }
      })
    },
    handleRemoveEditMainUrlFile (file) {
      var index = this.editData.mainUrl.indexOf(file)
      if (index > -1) {
        this.editData.mainUrl.splice(index, 1)
      }
    },
    editBannerUrlFileChange (file, fileList) {
      const form = new FormData()
      // 文件对象
      form.append('img', file.raw)
      api.upLoadImg(form).then((res) => {
        if (res.ret === 1) {
          let fileUrl = res.result
          file.url = fileUrl
          this.editData.bannerUrl.push(file)
        }
      })
    },
    handleRemoveEditBannerUrlFile (file) {
      var index = this.editData.bannerUrl.indexOf(file)
      if (index > -1) {
        this.editData.bannerUrl.splice(index, 1)
      }
    },
    handleEditClose () {
      this.dialog = ''
      this.clearEditCommodityData()
    },
    handleDeleteCommodity (row) {

    },
    handleAddSku (row) {
      this.$router.push(`/commodity/${row.id}/addSku`)
    },
    handleEditSku (row) {

    },
    beforeUploadImg (file) {
      console.log('beforeUploadImg')
      const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt1M = file.size / 1024 / 1024 < 1

      if (!isJPGOrPNG) {
        this.$message.error('上传图片只能是 JPG或者PNG 格式!')
      }
      if (!isLt1M) {
        this.$message.error('上传图片大小不能超过 1MB!')
      }
      return isJPGOrPNG && isLt1M
    },
    changeOnsaleStatus (row) {
      console.log(row.status)
      if (row.status === 1) {
        api.unSaleCommodity(row.id).then(res => {
          this.search()
        })
      } else {
        api.onSaleCommodity(row.id).then(res => {
          this.search()
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
  .container{
    padding: 10px 0 0 0 ;
  }
  .float-l{
    float: left;
  }
  .search{
    .el-form{
      width:100%;
      display:flex;
      flex-direction:row;
      justify-content:flex-start;
      flex-wrap:wrap;
      .el-form-item{
        width: 270px;
      }
    }
    width:100%;
  }
  .operation{
    margin-top:10px;
    float: left;
  }
  .el-tree{
    width:200px;
  }
</style>
